﻿using System;
using System.Drawing;
using System.Collections.Generic;

namespace Mazeball
{
    static class Game
    {
        public static Grid Grid { get; private set; }
        private static readonly List<IRenderable> _renderables = new List<IRenderable>();

        private static Ball _selectedBall;

        internal static void Initialize()
        {
            Grid = new Grid(GameSettings.Rows, GameSettings.Columns);
            _renderables.Add(Grid);

            NextTurn();
        }

        internal static void Render(Rectangle rect, Graphics g)
        {
            foreach (var renderable in _renderables)
            {
                renderable.Render(rect, g);
            }
        }

        static void NextTurn()
        {
            // add 3 random balls to the grid
            _renderables.Add(Grid.AddRandomBall());
            _renderables.Add(Grid.AddRandomBall());
            _renderables.Add(Grid.AddRandomBall());
        }

        public static void HandleClick(Point mousePos)
        {
            var cell = Grid.GetHitCell(mousePos);

            // if there is a ball in the selected ball, make the ball selected
            var ball = cell.Ball;
            if (ball != null)
            {
                _selectedBall = ball;
                _selectedBall.IsSelected = true;
            }
            else
            {
                // else if we had a selected ball before, do pathfinding and move ball
                if (_selectedBall != null)
                {
                    if (FindPath(_selectedBall.Cell, cell))
                    {
                        MoveBall(_selectedBall, cell);
                        EvaluateBalls();
                        NextTurn();
                    }
                    
                    // deselect ball
                    _selectedBall.IsSelected = false;
                    _selectedBall = null;    
                }
            }
        }

        private static void EvaluateBalls()
        {
            
        }

        private static void MoveBall(Ball selectedBall, GridCell cell)
        {
            
        }

        private static bool FindPath(GridCell cell, GridCell gridCell)
        {
            return true;
        }
    }
}
